set more off

*DGP index

*3 == Satisficing


local J `1'
local sigma `2'
local sigmax `3'


*Create choice and open numbers
*Order choices by free utility
*Keep searching if:
*max_{k \in set of searched goods}  alpha*x_{k} + beta*z_{k} + epsilon_{k}   < alpha*x_{j+1} + beta*r + epsilon_{j+1}

*Loop through goods
*One variable is current best
*If current best exceeds benchmark for next good, stop and choose current best
*If current best is less than benchmark, keep going

*At the end of loop, need to tag open boxes and chosen good

gen FU = x1*alpha1+x2*alpha2+x3*alpha3+x4*alpha4+x5*alpha5+x6*alpha6+x7*alpha7+x8*alpha8+x9*alpha9+x10*alpha10+x11*alpha11+x12*alpha12+x13*alpha13+x14*alpha14+epsilon
gen fullU = FU+beta*z

/*
*Search whenever FU > c

*Always open good with highest free utility
gsort ID -FU
by ID: gen utilrank = _n
gen open = (FU > c)
replace open = 1 if utilrank == 1

gen tempU = fullU-(1-open)*1e20
bys ID: egen maxU = max(tempU)
gen chosen = (tempU == maxU)
*/


*Stop searching if Ubar > c
gsort ID -FU
by ID: gen newID = _n

forvalues x = 1/`J' {
by ID: gen FU_`x' = FU[`x']
by ID: gen U_`x' = fullU[`x']
}

gen open = 1
gen Ucurr = U_1
local Jminus = `J'-1
forvalues x = 1/`Jminus' {
local z = `x'+1
replace open = 0 if Ucurr > c & newID == `z'
*If so, update utility if its bigger
replace Ucurr = U_`z' if U_`z' > Ucurr
}


*list ID newID FU Ucurr fullU c open in 1/100
*assert 1 == 0

gen tempU = fullU-(1-open)*1e20
bys ID: egen maxU = max(tempU)
gen chosen = (tempU == maxU)


bys ID: egen numchosen = sum(chosen)
tab numchosen 
bys ID chosen:egen firstID=min(newID)
replace chosen=0 if numchosen>1&chosen==1&firstID~=newID 
drop numchosen 
bys ID: egen numchosen = sum(chosen)
tab numchosen
drop firstID

egen maxchosen = max(numchosen)
local maxchosen = maxchosen
while(`maxchosen' != 1) {
drop numchosen maxchosen
replace tempU = tempU+.00001*uniform()
drop chosen
gen chosen = (tempU == maxU)
bys ID: egen numchosen = sum(chosen)
egen maxchosen = max(numchosen)
local maxchosen = maxchosen
}
drop numchosen maxchosen
